<template>
  <div class="login">
    <img class="login-logo" src="@/assets/images/zhkj.png" alt="logo" />
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">中恒智建云平台</h3>
      <div class="subtitle">智慧工程·高效管理</div>
      <el-form-item prop="username">
        <label class="login-label" for="login-username">账号</label>
        <el-input id="login-username" v-model="loginForm.username" type="text" auto-complete="off" placeholder="请输入账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <label class="login-label" for="login-password">密码</label>
        <el-input id="login-password" v-model="loginForm.password" type="password" auto-complete="off"
          placeholder="请输入密码" @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <label class="login-label" for="login-code">验证码</label>
        <el-input id="login-code" v-model="loginForm.code" auto-complete="off" placeholder="请输入验证码" style="width: 63%"
          @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button :loading="loading" size="medium" type="primary" style="width:100%;"
          @click.native.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right; margin-top: 10px;">
          <el-button type="text" @click="handleRegister" style="padding: 0;">立即注册</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 注册对话框 -->
    <el-dialog title="用户注册" :visible.sync="registerOpen" width="800px" append-to-body>
      <el-form ref="registerForm" :model="registerForm" :rules="registerRules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickName">
              <el-input v-model="registerForm.nickName" placeholder="请输入姓名" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect v-model="registerForm.deptId" :options="deptOptions" :show-count="true"
                :disable-branch-nodes="true" placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="registerForm.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="registerForm.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="账号" prop="userName">
              <el-input v-model="registerForm.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="registerForm.password" placeholder="请输入用户密码" type="password" maxlength="20"
                show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- <el-form-item label="用户性别">
              <el-select v-model="registerForm.sex" placeholder="请选择性别">
                <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item> -->
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item label="状态">
              <el-radio-group v-model="registerForm.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
                  :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item> -->
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="registerForm.postIds" multiple placeholder="请选择岗位">
                <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
                  :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->

        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="registerForm.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRegister">确 定</el-button>
        <el-button @click="cancelRegister">取 消</el-button>
      </div>
    </el-dialog>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright ©2024. All Rights Reserved 江西中恒地下空间科技有限公司 版权所有 备案号：赣ICP备2024045174号-</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg, registerUser, deptTreeSearch } from "@/api/login";
// import { getUser, addUser, deptTreeSelect } from "@/api/system/user";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getToken } from '@/utils/auth'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Login",
  // dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { Treeselect },
  data() {
    return {
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      // 注册对话框
      registerOpen: false,
      // 部门树选项
      deptOptions: undefined,
      // 岗位选项
      postOptions: [],
      // 注册表单
      registerForm: {},
      // 注册表单校验
      registerRules: {
        userName: [
          { required: true, message: "用户账号不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户姓名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    // 检查是否已经有token，如果有则直接跳转到首页
    const token = getToken();
    if (token) {
      this.$router.push({ path: this.redirect || "/" });
      return;
    }
    this.getCode();
    this.getCookie();
    this.getDeptTree();
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSearch().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 打开注册对话框 */
    handleRegister() {
      this.resetRegisterForm();
      this.registerOpen = true;
      // getUser().then(response => {
      //   this.postOptions = response.posts;
      //   this.registerOpen = true;
      // });
    },
    /** 重置注册表单 */
    resetRegisterForm() {
      this.registerForm = {
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [10] // 固定传10
      };
      if (this.$refs.registerForm) {
        this.$refs.registerForm.resetFields();
      }
    },
    /** 取消注册 */
    cancelRegister() {
      this.registerOpen = false;
      this.resetRegisterForm();
    },
    /** 提交注册 */
    submitRegister() {
      this.$refs["registerForm"].validate(valid => {
        if (valid) {
          // 固定传角色ID为10
          this.registerForm.roleIds = [10];
          registerUser(this.registerForm).then(response => {
            this.$modal.msgSuccess("注册成功");
            this.registerOpen = false;
            this.resetRegisterForm();
          }).catch(() => {
            // 错误处理已在 request 拦截器中处理
          });
        }
      });
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || "/" }).catch(() => { });
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-end;
  height: 100vh;
  min-height: 100vh;
  width: 100vw;
  box-sizing: border-box;
  padding-top: 0;
  padding-bottom: 0;
  // background-image: url("../assets/images/bg.svg"); // 移除原背景
  // background-size: cover;
  // background-position: center;
  // background-repeat: no-repeat;
  // background-attachment: fixed;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    background-image: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.2)), url("../assets/images/bg.svg");
    background-size: cover;
    background-position: 0% 50%;
    background-repeat: no-repeat;
    background-attachment: fixed;
    transform: scaleX(-1);
    pointer-events: none;
    background-blend-mode: lighten;
  }

  >* {
    position: relative;
    z-index: 1;
  }

  .login-logo,
  .login-form {
    margin-right: 8vw;
    align-self: flex-end;
  }

  @media (max-width: 900px) {

    .login-logo,
    .login-form {
      margin-right: 0;
      align-self: center;
    }

    justify-content: center;
    align-items: center;
  }
}

.login-logo {
  position: absolute;
  top: 32px;
  left: 40px;
  right: auto;
  width: 200px;
  height: auto;
  z-index: 10;
  border-radius: 10px;
  /* 完全透明，无阴影无背景 */
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #2c3142;
  font-size: 38px;
  font-weight: 600;
  letter-spacing: 5px;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.subtitle {
  text-align: center;
  color: #7a7e8a;
  font-size: 15px;
  font-weight: 400;
  letter-spacing: 2px;
  margin-bottom: 24px;
  margin-top: -18px;
}

.login-form {
  // border-radius: 18px;
  // background: rgba(255, 255, 255, 0.72);
  width: 400px;
  padding: 32px 32px 12px 32px;
  margin: 0 8vw;
  // box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
  position: relative;
  z-index: 2;
  // backdrop-filter: blur(12px);
  // transition: box-shadow 0.3s;
  color: #333;
  overflow: hidden;
  /* 渐变边框 */
  // box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18), 0 0 0 4px rgba(255, 255, 255, 0.08) inset;

  .el-input {
    height: 38px;

    input {
      height: 38px;
      background: #f7f8fa;
      border-radius: 8px;
      border: 1px solid #e0e0e0;
    }

    input::placeholder {
      color: #bbb;
      opacity: 1;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
    color: #ccc;
  }

  .login-label {
    display: block;
    font-size: 15px;
    color: #888;
    margin-bottom: 4px;
    margin-left: 2px;
    font-weight: 500;
    letter-spacing: 1px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #ccc;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

@media (max-width: 900px) {
  .login {
    padding-top: 4vh;
    padding-bottom: 4vh;
  }

  .login-logo {
    top: 12px;
    left: 12px;
    right: auto;
    width: 80px;
  }

  .login-form {
    margin: 0;
  }
}
</style>
